package com.yeyks.task;

import cn.hutool.core.date.DateUtil;
import com.yeyks.common.constants.CouponConst;
import com.yeyks.other.dal.dao.CouponInfoMapper;
import com.yeyks.other.dal.domain.CouponInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author shuai
 * @date 2019/10/29 13:43
 */
@Component
@Slf4j
public class CheckCouponTask {
    @Autowired
    CouponInfoMapper couponInfoMapper;

    @Scheduled(cron = "${schedule.coupon.job}")
    private void checkCouponTask() {
        log.info("检查优惠券执行-----------，time = {}", DateUtil.formatDateTime(new Date()));
        try {
            List<Integer> statusList = new ArrayList<>();
            statusList.add(CouponConst.statusInitialized);
            statusList.add(CouponConst.statusGetting);
            List<CouponInfo> couponInfoList = couponInfoMapper.selectByStatus(statusList);
            for (CouponInfo couponInfo : couponInfoList) {
                couponInfo.setGmtModified(new Date());
                Date now = new Date();
                if (couponInfo.getStatus() == CouponConst.statusInitialized) {
                    if (now.getTime() > couponInfo.getValidStart().getTime() &&
                            now.getTime() < couponInfo.getValidEnd().getTime()) {
                        // 时间到达有效期内
                        couponInfo.setStatus(CouponConst.statusGetting);
                        couponInfoMapper.updateByPrimaryKey(couponInfo);
                    } else if (couponInfo.getValidEnd().getTime() < now.getTime()) {
                        // 时间已结束
                        couponInfo.setStatus(CouponConst.statusFinished);
                        couponInfoMapper.updateByPrimaryKey(couponInfo);
                    }
                } else if (couponInfo.getStatus() == CouponConst.statusGetting) {
                    if (couponInfo.getValidEnd().getTime() < now.getTime()) {
                        // 时间已结束
                        couponInfo.setStatus(CouponConst.statusFinished);
                        couponInfoMapper.updateByPrimaryKey(couponInfo);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("检查优惠券结束");
    }
}
